package com.java.simple.study.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhoujunlin
 * @date 2023年04月17日 14:11
 * @desc
 */
@Slf4j
public class SocketServerMultipleThread {

    @SneakyThrows
    public static void main(String[] args) {
        ServerSocket serverSocket = new ServerSocket(9090);
        while (true) {
            log.info("等待客户端链接");
            // 阻塞等待
            Socket so = serverSocket.accept();
            log.info("客户端链接成功");
            new Thread(() -> {
                try {
                    handlerClient(so);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private static void handlerClient(Socket so) throws IOException {
        InputStream inputStream = so.getInputStream();
        byte[] bytes = new byte[1024];
        // 阻塞读取客户端数据
        int len = inputStream.read(bytes);
        log.info("接受到客户端数据:{}", new String(bytes, 0, len));
        so.getOutputStream().write("ok".getBytes());
        so.getOutputStream().flush();
    }

}
